<?php

namespace app\chats\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\Request;
use app\service\Token;

class Login extends Controller
{
    // 公共
    public function _initialize()
    {
        if (Session::has('admin', 'mmjtChats')) {
            $request = Request::instance();

            header('location:' . $request->domain() . $request->baseFile() . '/chat');
        }
    }


    public function index()
    {
        if (request()->isAjax()) {
            $name = htmlspecialchars_decode(strip_tags(input('post.name')));
            $password = htmlspecialchars_decode(strip_tags(input('post.password')));
            $captcha = strip_tags(htmlspecialchars_decode(input('post.yzm')));

            if ($name && $password) {
                if (!$captcha) {
                    return ['err' => '请输入验证码'];
                }
                if (!captcha_check($captcha)) {
                    return ['err' => '验证码错误'];
                };

                $kefu = Db::name('config_system')->where(['title' => 'id'])->value('content');
                $kefu = intval($kefu);

                $admin = Db::name('user')->where(['id' => $kefu, 'phone' => $name, 'password' => $password])->find();

                if ($admin) {
                    if ($admin['is_banned'] == 1 && strtotime($admin['banned_end_time']) > time()) {
                        $data = ["err" => '账户被禁用'];
                    } else {
                        Db::name('user')->where(['id' => $admin['id']])->update(['chats_admin_status' => 1, 'chats_admin_time' => time()]);

                        Session::set('admin', $admin, 'mmjtChats');
                        $data = ["ret" => '登录成功,正在跳转...', "data" => $admin['id']];


                        $tokenData = array(
                            'userid' => $admin['id'],
                            'time' => $admin['last_login_time'],
                            'sex' => $admin['sex']
                        );
                        $token = Token::createToken($tokenData);
                        if($token['status']==200){
                            $data['token'] = $token['token'];
                        }
                    }
                } else {
                    $data = ["err" => '账户和密码错误'];
                }
            } else {
                $data = ['err' => '请输入信息'];
            }
            return json($data);
        } else {
            // $url = $_SERVER['REQUEST_SCHEME'] . "://" . $_SERVER['SERVER_NAME'];

            // $url = str_replace('/index.php', '', $url) . '/chat';
            
            $url = '/chat';

            $this->assign('url', $url);

            return $this->fetch();
        }
    }
}
